//
//  BluetoothViewController.m
//  FaceTo
//
//  Created by chijia on 2017/6/18.
//  Copyright © 2017年 chengbangming. All rights reserved.
//

#import "BluetoothViewController.h"
#import "FTFriendsListViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "YBPopupMenu.h"
#import "FTBLSwitchViewCell.h"
#import "CanEditViewCell.h"
#import "FTBLHeaderView.h"
#import "FTBLFreshHeaderView.h"
#import "FTBLPeripheralViewCell.h"
#import "AppDelegate.h"
#import "FTFriendsListViewController.h"
#import "GNRBLEFriendsManager.h"

#define TITLES @[@"设置", @"关于软件", @"退出登录"]
#define ICONS  @[@"motify",@"delete",@"saoyisao",@"pay"]

@interface BluetoothViewController ()<YBPopupMenuDelegate, UITableViewDelegate, UITableViewDataSource>
{
    BOOL isBluetoothOn; // 是否开启蓝牙连接（tableView的section=2）
    BOOL scanning; //扫描中
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *peripherals; // 存储搜索到的手机外设

@end

@implementation BluetoothViewController

//- (NSMutableArray *)peripherals
//{
//    if (!_peripherals) {
//        _peripherals = [NSMutableArray array];
//    }
//    return _peripherals;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WhiteColor;
    
    _peripherals = [NSMutableArray array];
    
    [self initNavAndTab];
    
    [self initUI];
    
    
}

// 初始化navbar
- (void)initNavAndTab
{
    // title设为空
    self.title = @"";
    self.tabBarItem.title = @"蓝牙";
    
    // nav左边按钮
    UIBarButtonItem *menubtn = [UIBarButtonItem itemWithImageName:@"menu" highImageName:@"menu" target:self action:@selector(menuClick:)];
    UIBarButtonItem *logoBtn = [UIBarButtonItem itemWithImageName:@"small_md" highImageName:@"small_md" target:self action:nil];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:[UIButton buttonWithType:UIButtonTypeCustom]];
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:menubtn, item, logoBtn, nil];
    
    // nav右边按钮
    UIBarButtonItem *checkin = [UIBarButtonItem itemWithImageName:@"checkin" highImageName:@"checkin" target:self action:@selector(menuClick:)];
    UIBarButtonItem *friends = [UIBarButtonItem itemWithImageName:@"friends" highImageName:@"friends" target:self action:nil];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:[UIButton buttonWithType:UIButtonTypeCustom]];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:friends, item1, checkin, nil];
    
    // tab选中背景色
    CGSize indicatorImageSize = CGSizeMake(self.tabBarController.tabBar.bounds.size.width/self.tabBarController.tabBar.items.count, self.tabBarController.tabBar.bounds.size.height);
    self.tabBarController.tabBar.selectionIndicatorImage = [self drawTabBarItemSelectedBgImageWithSize:indicatorImageSize];
}

// 设置界面
- (void)initUI
{
    isBluetoothOn = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-50-64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = Color(237, 237, 237);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_tableView];
}

// 点击打开侧滑
- (void)menuClick:(UIButton *)sender
{
    //    [YBPopupMenu showRelyOnView:sender titles:TITLES icons:nil menuWidth:120 delegate:self];
    CKLeftSlideViewController *leftSlide = (CKLeftSlideViewController *)[((AppDelegate *)[UIApplication sharedApplication].delegate) leftSlideVc];
    [leftSlide openLeftView];
}

// 自定义tabbar效果
- (UIImage *)drawTabBarItemSelectedBgImageWithSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextSetRGBFillColor(ctx, 252.0/255.0, 215.0/255.0, 51.0/255.0, 1);
    CGContextFillRect(ctx, CGRectMake(0, 0, size.width, size.height));
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    NSLog(@"点击了 %@ 选项",TITLES[index]);
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;//isBluetoothOn ? 2 : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    return _peripherals.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 2) {
            
            static NSString *identifier = @"cell1";
            
            CanEditViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            
            if (cell == nil) {
                cell = [[CanEditViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.textLab.text = @"邀请好友";
            cell.selectionStyle = NO;
            return cell;
            
        } else {
            
            static NSString *identifier = @"cell2";
            
            FTBLSwitchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[FTBLSwitchViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.titlelab.text = indexPath.row == 0 ? @"开启蓝牙连接" : @"开启网络连接";
            cell.selectionStyle = NO;
            cell.row = indexPath.row;
            
            cell.block = ^(BOOL isOn, NSInteger row) {
                isBluetoothOn = isOn;
                
                if (row == 0 && isBluetoothOn) {  // 蓝牙互连
                    
                    [self myBluetooth];
                } else if (row == 1 && !isBluetoothOn) {  // 网络互连
                    
                }
            };
            return cell;
        }
    } else {
        
        static NSString *identifier = @"cell3";
        
        FTBLPeripheralViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell == nil) {
            cell = [[FTBLPeripheralViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        
        cell.selectionStyle = NO;
        
        if (indexPath.row < self.peripherals.count) {
            GNRPeripheral * per = self.peripherals[indexPath.row];
            cell.namelbl.text = per.name;
            cell.statelbl.text = per.identifier;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 2) {
        
        FTFriendsListViewController *vc = [[FTFriendsListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        FTBLFreshHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"Header1"];
        if (!headerView) {
            headerView = [[FTBLFreshHeaderView alloc] initWithReuseIdentifier:@"Header1"];
        }
        return headerView;
    }
    FTBLHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"Header"];
    if (!headerView) {
        headerView = [[FTBLHeaderView alloc] initWithReuseIdentifier:@"Header"];
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    }
    return kSCREEN_WIDTH/2.5 + 110;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark 蓝牙事件
- (void)myBluetooth
{
    if (!scanning) {
        
        scanning = YES;
        //        [UIAlertView alertViewWithTitle:@"如搜索不到，请重新开启蓝牙" message:nil cancelButtonTitle:@"知道了"];
        //        [_scanBtn setTitle:@"扫描中,点击停止扫描" forState:UIControlStateNormal];
        [SVProgressHUD show];
        [self scanPeripheral];
        
    } else {
        scanning = NO;
        [self stopScan];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self stopScan];
}

- (void)scanPeripheral
{
    [[GNRBLEFriendsManager manager] startScanWithScanCompletion:^(NSMutableArray<GNRPeripheral *> *peripherals) {
        
        _peripherals = peripherals;
        [_tableView reloadData];
        [SVProgressHUD dismiss];
        
    } error:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
    
    //某一设备断开连接
    [GNRBLEFriendsManager manager].disConnetBlock = ^(GNRPeripheral *peripheral, NSError *error) {
        [_tableView reloadData];
    };
}

- (void)stopScan
{
    [[GNRBLEFriendsManager manager] stopScan];
}
@end
